package com.yunji.web.system;

import com.google.common.collect.Maps;
import com.yunji.common.annotation.Log;
import com.yunji.common.base.BaseController;
import com.yunji.common.base.response.Response;
import com.yunji.common.base.response.ResponseHelper;
import com.yunji.common.constant.UserCode;
import com.yunji.common.enums.common.BusinessType;
import com.yunji.common.model.bo.TreeSelect;
import com.yunji.common.model.domain.SysMenuDO;
import com.yunji.common.utils.StringUtils;
import com.yunji.system.context.SystemContext;
import com.yunji.system.service.ISysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 菜单信息
 *
 * @author ruoyi
 */
@Api(tags = "菜单信息")
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {
    @Autowired
    private ISysMenuService menuService;

    /**
     * 获取菜单列表
     */
    @ApiOperation("获取菜单列表")
    @PreAuthorize("@ss.hasPermi('system:menu:list')")
    @GetMapping("/list")
    public Response<List<SysMenuDO>> list(SysMenuDO menu) {
        List<SysMenuDO> menus = menuService.selectMenuList(menu, SystemContext.getUserId());
        return ResponseHelper.success(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @ApiOperation("根据菜单编号获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:menu:query')")
    @GetMapping(value = "/{menuId}")
    public Response<SysMenuDO> getInfo(@PathVariable Long menuId) {
        return ResponseHelper.success(menuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @ApiOperation("获取菜单下拉树列表")
    @GetMapping("/treeselect")
    public Response<List<TreeSelect>> treeselect(SysMenuDO menu) {
        List<SysMenuDO> menus = menuService.selectMenuList(menu, SystemContext.getUserId());
        return ResponseHelper.success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @ApiOperation("加在对应角色菜单列表树")
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public Response<Map<String, Object>> roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysMenuDO> menus = menuService.selectMenuList(SystemContext.getUserId());
        Map<String, Object> map = Maps.newHashMap();
        map.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        map.put("menus", menuService.buildMenuTreeSelect(menus));
        return ResponseHelper.success(map);
    }

    /**
     * 新增菜单
     */
    @ApiOperation("新增菜单")
    @PreAuthorize("@ss.hasPermi('system:menu:add')")
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Response<Long> add(@Validated @RequestBody SysMenuDO menu) {
        if (!menuService.checkMenuNameUnique(menu)) {
            return ResponseHelper.failure("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserCode.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return ResponseHelper.failure("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(SystemContext.getUsername());
        Assert.isTrue(menuService.insertMenu(menu) > 0, "新增失败");
        return ResponseHelper.success(menu.getMenuId());
    }

    /**
     * 修改菜单
     */
    @ApiOperation("修改菜单")
    @PreAuthorize("@ss.hasPermi('system:menu:edit')")
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public Response<String> edit(@Validated @RequestBody SysMenuDO menu) {
        if (!menuService.checkMenuNameUnique(menu)) {
            return ResponseHelper.failure("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserCode.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return ResponseHelper.failure("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            return ResponseHelper.failure("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SystemContext.getUsername());
        Assert.isTrue(menuService.updateMenu(menu) > 0, "修改失败");
        return ResponseHelper.success();
    }

    /**
     * 删除菜单
     */
    @ApiOperation("删除菜单")
    @PreAuthorize("@ss.hasPermi('system:menu:remove')")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public Response<String> remove(@PathVariable("menuId") Long menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            return ResponseHelper.failure("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId)) {
            return ResponseHelper.failure("菜单已分配,不允许删除");
        }
        Assert.isTrue(menuService.deleteMenuById(menuId) > 0, "删除失败");
        return ResponseHelper.success();
    }
}